<script setup>
	import { defineProps, ref, watchEffect } from 'vue'
	import { message } from 'ant-design-vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import { useCustomQueryStore } from '@/views/plugin/dashboard/store/customQuery'
	import { storeToRefs } from 'pinia'
	import ChartPreview from './ChartPreview.vue'

	const store = useCustomQueryStore()
	const { queryResult } = storeToRefs(store)

	const props = defineProps({
		dataConnectorId: {
			type: String,
			required: true
		},
		sql: {
			type: String,
			required: true
		},
		params: {
			type: Array,
			default: () => []
		}
	})

	// 加载状态
	const loading = ref(false)
	const currentView = ref('table')

	// 执行预览查询
	const executePreview = async () => {
		if (!props.sql.trim()) {
			message.error('SQL查询语句不能为空')
			return
		}

		try {
			loading.value = true
			const res = await dataConnectorApi.preview({
				id: props.dataConnectorId,
				sql: props.sql,
				params: props.params
			})
			store.updateQueryResult(res.data || [])
		} catch (error) {
			message.error('预览查询失败：' + (error.message || '未知错误'))
		} finally {
			loading.value = false
		}
	}

	const columns = ref()
	watchEffect(() => {
		columns.value =
			queryResult.value.length > 0
				? Object.keys(queryResult.value[0]).map((key) => ({
						title: key,
						dataIndex: key,
						width: 400,
						minWidth: 200,
						maxWidth: 800,
						resizable: true
					}))
				: []
	})
	defineExpose({
		executePreview
	})
</script>

<template>
	<div class="mt-4">
		<!-- <div class="view-controls mb-4">
			<a-radio-group v-model:value="currentView" button-style="solid">
				<a-radio-button value="table">表格视图</a-radio-button>
				<a-radio-button value="chart">图表视图</a-radio-button>
			</a-radio-group>
		</div> -->

		<div v-show="currentView === 'table'">
			<a-table
				:columns="columns"
				border
				:data-source="queryResult"
				:scroll="{ x: 1500 }"
				:pagination="{ pageSize: 20 }"
				size="small"
				:class="'compact-table'"
			/>
		</div>

		<div v-show="currentView === 'chart'">
			<ChartPreview :data-connector-id="dataConnectorId" :sql="sql" :params="params" />
		</div>
	</div>
</template>

<style scoped>
	.compact-table :deep(.ant-table-thead > tr > th),
	.compact-table :deep(.ant-table-tbody > tr > td) {
		padding: 4px 8px;
		font-size: 13px;
	}

	.compact-table :deep(.ant-table-tbody > tr) {
		height: 32px;
	}
</style>
